package com.indeep.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import com.indeep.user.mapper.AppInvitationCodeUserMapper;
import com.indeep.user.mapper.AppInvitationCodeMapper;
import com.indeep.user.mapper.po.AppInvitationCodePO;
import com.indeep.user.dto.CodeDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.indeep.user.service.AppInvitationCodeService;
import java.util.Date;

@Service
@Transactional
public class AppInvitationCodeServiceImpl implements AppInvitationCodeService {
    
    @Autowired
    private AppInvitationCodeMapper appInvitationCodeMapper;
    
    @Autowired
    private AppInvitationCodeUserMapper appInvitationCodeUserMapper;
    
    /**
     * 校验邀请码
     *
     * @param dto CodeDTO
     * @return 检验成功返回邀请码ID，失败返回null
     */
    @Override
    public Integer checkCode(CodeDTO dto) {
        // 校验邀请码是否有效
        QueryWrapper<AppInvitationCodePO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("code", dto.getCode());
        AppInvitationCodePO codeDO = appInvitationCodeMapper.selectOne(queryWrapper);
        
        if (codeDO == null) return null;
        
        // 邀请码剩余可邀请人数不足
        if (codeDO.getCurNum() <= 0) {
            return -1;
        }
        // 超过邀请码有效期
        if (codeDO.getExpireTime().compareTo(new Date()) <= 0) {
            return -2;
        }
        return codeDO.getId();
    }
}
